package com.lavida.project.system.contractmana.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.lavida.common.utils.security.ShiroUtils;
import com.lavida.framework.web.controller.BaseController;
import com.lavida.framework.web.page.TableDataInfo;
import com.lavida.project.common.DownLoadUtils;
import com.lavida.project.system.contractmana.domain.Contractmana;
import com.lavida.project.system.contractmana.service.ContractmanaService;
import com.lavida.project.system.user.domain.User;
import com.lavida.project.system.user.service.IUserService;
import com.mchange.lang.StringUtils;
@Controller
@RequestMapping("system/contractmana")
public class ContractmanaController extends BaseController{
	private String prefix = "system/contractmana";

	@Autowired
	private ContractmanaService cons;
	@Autowired
	private IUserService userService;
	@RequiresPermissions("data:contractmana:view")
	@RequestMapping()
	public String contractmana(ModelMap mmap) {
		User user  = ShiroUtils.getSysUser();
		User user1 = userService.selectUserById(user.getUserId());
		mmap.put("user", user1);
		return prefix + "/contractmana";
	}
	@RequiresPermissions("data:contractmana:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(Contractmana contractmana,HttpServletRequest request) {
		String str = request.getParameter("insurance_name");
		if(str!="") {
			contractmana.setDangan_id(str);
			contractmana.setContract_id(str);
			contractmana.setInsurance_name(str);
			contractmana.setInsurance_com(str);
		}	
		startPage();
		List<Contractmana> selectContractmana = cons.selectContractmana(contractmana);	
		return getDataTable(selectContractmana);
	}
	@RequestMapping("/add")
	public String add() {
		return prefix + "/add";
	}
	@RequiresPermissions("data:contractmana:add")
	@RequestMapping("/showAddCont")
	public String showAddCont(Contractmana contractmana,MultipartFile file,HttpServletRequest request) throws IllegalStateException, IOException {
		/*System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>"+file.toString());
		System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>"+contractmana.toString());*/
		try {
			if(file.isEmpty()) {
				contractmana.setAnnex("");
			    contractmana.setAnnexPath("");
			}else {
				String path=filePath(request);
			     //System.out.println("path>>>>>>"+path);
			     String originalFilename=file.getOriginalFilename(); 
			     //System.out.println(originalFilename+"=================");
			     String uuid=UUID.randomUUID().toString().replace("-","");
			     String filename=uuid+"_"+originalFilename.replace(" ", "");
			     file.transferTo(new File(path,filename));
			     contractmana.setAnnex(originalFilename.replace(" ", ""));
			     contractmana.setAnnexPath(filename.replace(" ", ""));
			}
			System.out.println("contractmana>>>>>>>>>>>>"+contractmana);
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		 cons.insertContract(contractmana);
		 return "redirect:/system/contractmana";
	}
	
	@RequiresPermissions("data:contractmana:delete")
	@PostMapping("/delete")
	@ResponseBody
	public Map<String, String> delete(@RequestParam("ids[]")int[] ids){
		Map<String, String> result = new HashMap<String, String>();
		cons.deleteContract(ids);
		result.put("msg", "删除成功");
		return result;
	}
	@PostMapping("/getContract")
	@ResponseBody
	public Map<String, Object> getContractmana(int id){
		Map<String, Object> result = new HashMap<>();
		Contractmana contractmana = cons.getContractmana(id);
		result.put("contractmana", contractmana);
		return result;
	}
	@RequiresPermissions("data:contractmana:update")
	@PostMapping("/updateContract")
	public String updateContractmana(@RequestParam(value = "annex3", required = false)MultipartFile file,
			Contractmana contractmana,HttpServletRequest request) throws IllegalStateException, IOException {
		Map<String, Object> result = new HashMap<String,Object>(); 
		/*System.out.println("修改>>>>>>>>>>>>>>>>>>>>>>>>"+file.toString());*/
		/*System.out.println("修改>>>>>>>>>>>>>>>>>>>>>>>>"+contractmana.toString());*/
		Contractmana contractmana2 = cons.getContractmana(contractmana.getId());
		if(file.isEmpty()) {
			contractmana.setAnnex(contractmana2.getAnnex());
			contractmana.setAnnexPath(contractmana2.getAnnexPath());
		}else {
			String path = filePath(request);
			String originalFilename=file.getOriginalFilename();
			String uuid=UUID.randomUUID().toString().replace("-","");
		    String filename=uuid+"_"+originalFilename.replace(" ", "");
		    file.transferTo(new File(path,filename));
		    contractmana.setAnnex(originalFilename.replace(" ", ""));
		    contractmana.setAnnexPath(filename.replace(" ", ""));
		}
		cons.updateContract(contractmana);	
		return "redirect:/system/contractmana";
	}
	@RequestMapping("/download")
	public void download(String fileRealname,String fileVmname,HttpServletResponse response,HttpServletRequest request) {
        String string=request.getHeader("User-Agent");
        String Uploadfilename=null;
        try {
			Uploadfilename= DownLoadUtils.getFileName(string,fileVmname);
	        response.setHeader("Content-disposition","attachment;filename="+Uploadfilename);
	        //response.setHeader("Content-disposition", "attachment;filename=\"" + fileName +"\"");
	        String fileVmPath=filePath(request);
	        System.out.println(String.format("%s\\%s",fileVmPath,fileRealname));
	        ServletOutputStream s = response.getOutputStream();
	        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(String.format("%s/%s",fileVmPath,fileRealname)));
	        int a;
	        byte[] bytes=new byte[1024];
	        while ((a = bufferedInputStream.read(bytes))!=-1){
	            s.write(bytes,0,a);
	            System.out.println("下载成功");
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	 private static String filePath(HttpServletRequest request){
	        // 先获取到要上传的文件目录
	        String path = request.getSession().getServletContext().getRealPath("/annex");

	        // 创建File对象，一会向该路径下上传文件
	        File file = new File(path);
	        System.out.println(file);
	        // 判断路径是否存在，如果不存在，创建该路径
	        if(!file.exists()) {
	            file.mkdirs();
	        }
	        return path;
	    }
}
